<?
require_once('includes/config.php');
require_once('includes/functions/func.global.php');
require_once('includes/functions/func.thumbs.php');
require_once('includes/classes/class.template_engine.php');
require_once('includes/lang/lang_'.$config['lang'].'.php');

// Start the session
session_start();

// Connect to the database
db_connect($config);

// Check if the user has a remember cookie set
checkremember($config);

// Check that the user is logged in
logincheck();

// Get site categories
$cats = get_cats($config);

// Get categories for selection
$field_cats = $cats;
unset($field_cats[0]);

if(isset($_GET['story_url']))
{
	$_POST['story_url'] = $_GET['story_url'];
}

// Check if a url has been submitted
if(isset($_POST['story_url']))
{
	if(!eregi('^http(s?)://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\._\?\,\'/\\\+&%\$#\=~\-])*$',$_POST['story_url']))
	{
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/add_story_step1.html");
		$page->SetLoop ('CATS', $cats);
		$page->SetParameter ('FIELD_URL',$_POST['story_url']);
		$page->SetParameter ('URL_ERROR','Please enter a valid url');
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Submit Story'));
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->CreatePageEcho($lang,$config);
		exit;
	}
	else
	{
		if(!isset($_POST['dupe']))
		{
			$dupe_check = mysql_fetch_row(mysql_query("SELECT story_id FROM `".$config['db']['pre']."stories` WHERE story_url='".addslashes($_POST['story_url'])."' LIMIT 1"));
			
			if($dupe_check[0])
			{
				// Initiate stories array
				$stories = array();
				
				// Retreive stories from the database
				$query = "SELECT story_id,story_title,story_desc,story_cat,story_digs,story_url,story_comments,user_name,user_id,story_thumb,story_time FROM ".$config['db']['pre']."stories WHERE story_url='".addslashes($_POST['story_url'])."' LIMIT 10";
				$query_result = @mysql_query ($query) OR error(mysql_error(), __LINE__, __FILE__, 0, '', '');
				while ($info = @mysql_fetch_array($query_result))
				{
					$stories[$info['story_id']] = $info;
					$stories[$info['story_id']]['dugg'] = 0;
					$stories[$info['story_id']]['buried'] = 0;
					$stories[$info['story_id']]['cat_title'] = $cats[$info['story_cat']]['cat_title'];
					$stories[$info['story_id']]['cat_id'] = $info['story_cat'];
					$stories[$info['story_id']]['ago'] = time_taken((time()-$info['story_time']));
					
					if($config['mod_rewrite'] == 1)
					{
						$stories[$info['story_id']]['story_link'] = $config['site_url'].'stories/'.$info['story_id'].'/'.modrewriteurl($info['story_title']).'.html';
						$stories[$info['story_id']]['cat_link'] = $config['site_url'].'view/'.$info['story_cat'].'/'.modrewriteurl($cats[$info['story_cat']]['cat_title']).'/1.html';
						$stories[$info['story_id']]['user_link'] = $config['site_url'].'users/'.$info['user_id'].'/'.$info['user_name'].'/1.html';
					}
					else
					{
						$stories[$info['story_id']]['story_link'] = $config['site_url'].'story.php?id='.$info['story_id'];
						$stories[$info['story_id']]['cat_link'] = $config['site_url'].'cat.php?i='.$info['story_cat'];
						$stories[$info['story_id']]['user_link'] = $config['site_url'].'profile.php?id='.$info['user_id'];
					}
					
					// Construct where string for looking up digs
					if(!isset($_SESSION['dugg'][$info['story_id']]))
					{
						if(isset($story_where))
						{
							$story_where.= " OR story_id='".$info['story_id']."'";
						}
						else
						{
							$story_where = "story_id='".$info['story_id']."'";
						}
					}
					
					if(!isset($_SESSION['bury'][$info['story_id']]))
					{
						if(isset($story_where2))
						{
							$story_where2.= " OR story_id='".$info['story_id']."'";
						}
						else
						{
							$story_where2 = "story_id='".$info['story_id']."'";
						}
					}
				}
			
				$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/add_story_dupe.html");
				$page->SetLoop ('CATS', $cats);
				$page->SetLoop ('STORIES',$stories);
				$page->SetParameter ('STORY_URL_FIELD', $_POST['story_url']);
				$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Submit Story'));
				$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
				$page->CreatePageEcho($lang,$config);
				exit;
			}
		}
	
		// Initiate the variables
		$title_field = '';
		$desc_field = '';
		$title_error = '';
		$desc_error = '';
		$category_error = '';
	
		if(isset($_POST['story_title']))
		{
			// Set the error count to 0
			$errors = 0;
			
			// Strip HTML and limit title and description
			$_POST['story_title'] = strip_tags($_POST['story_title']);
			$_POST['story_title'] = substr($_POST['story_title'],0,80);
			$_POST['story_desc'] = strip_tags($_POST['story_desc']);
			$_POST['story_desc'] = substr($_POST['story_desc'],0,400);
			
			// Check the story tile isn't less than 4 chars long
			if(strlen($_POST['story_title']) < 4)
			{
				$errors++;
				$title_error = 'Story title must be 4 or more characters long';
			}
			
			// Check that they have select a category
			if(!isset($_POST['story_category']))
			{
				$errors++;
				$category_error = 'Please choose a category';
			}
			
			// Check the story desciption isn't less than 10 chars long
			if(strlen($_POST['story_desc']) < 10)
			{
				$errors++;
				$desc_error = 'Story description must be at least 10 characters long';
			}
			
			// Check that there are no errors
			if($errors == 0)
			{
				$thumb_insert = '';
			
				if($config['vidthumb'])
				{
					// Check if the story is from youtube
					if(eregi('http://www.youtube.com/watch\?v=',$_POST['story_url']))
					{
						$video_id = str_replace('http://www.youtube.com/watch?v=','',$_POST['story_url']);
						$video_id = str_replace('&eurl=','',$video_id);
						
						if($video_id)
						{
							if(file_exists('images/thumbs/youtube'.$video_id.'.jpg'))
							{
								$thumb_insert = 'youtube'.$video_id;
							}
							else
							{
								$thumb = getyoutubethumb($video_id);
								
								if($thumb != '')
								{
									if(@is_writable('images/thumbs/'))
									{
										if(@copy($thumb,'images/thumbs/youtube'.$video_id.'.jpg'))
										{
											$thumb_insert = 'youtube'.$video_id;
										}
									}
								}
							}
						}
					}
					// Check if the story is from google video
					elseif (eregi('http://video.google.([a-z.]{2,5})/videoplay\?docid=',$_POST['story_url']))
					{
						$video_id = eregi_replace('http://video\.google\.([a-z].{3,5})/videoplay\?docid=','',$_POST['story_url']);
						$tail = strstr($video_id, '&');
						if ($tail) 
						{
							$video_id = str_replace($tail,'',$video_id);
						}
											
						if ($video_id)
						{
							if(file_exists('images/thumbs/google'.$video_id.'.jpg'))
							{
								$thumb_insert = 'google'.$video_id;
							}
							else
							{
								$thumb = getgooglethumb($video_id);
													
								if($thumb != '')
								{
									if(@is_writable('images/thumbs/'))
									{
										if(@copy($thumb,'images/thumbs/google'.$video_id.'.jpg'))
										{
											$thumb_insert = 'google'.$video_id;
										}
									}
								}
							}
						}
					}
				}
			
				// Insert the story into the database
				mysql_query("INSERT INTO `".$config['db']['pre']."stories` ( `story_id` , `user_id` , `user_name` , `story_url` , `story_title` , `story_desc` , `story_cat` , `story_rating` , `story_digs` , `story_time` , `story_thumb` ) VALUES ('', '".$_SESSION['duser']['id']."', '".$_SESSION['duser']['name']."', '".addslashes($_POST['story_url'])."', '".addslashes($_POST['story_title'])."', '".addslashes($_POST['story_desc'])."', '".addslashes($_POST['story_category'])."', '9999', '1', '".time()."','".addslashes($thumb_insert)."');");
				// Self-Digg
				mysql_query("INSERT INTO `".$config['db']['pre']."digs` ( `story_id` , `user_id` ) VALUES ('".addslashes(mysql_insert_id())."', '".$_SESSION['duser']['id']."');");
			
				// Redirect them to the index
				header("Location: index.php");
				exit;
			}
			else
			{
				// Set title and description for template fields
				$title_field = $_POST['story_title'];
				$desc_field = $_POST['story_desc'];
				
				if(isset($_POST['story_category']))
				{
					$field_cats[$_POST['story_category']]['checked'] = 1;
				}
			}
		}
	
		// Output Step2 of add story template
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/add_story_step2.html");
		$page->SetLoop ('CATS', $cats);
		$page->SetLoop ('FIELD_CATS', $field_cats);
		$page->SetParameter ('TITLE_ERROR', $title_error);
		$page->SetParameter ('DESC_ERROR', $desc_error);
		$page->SetParameter ('CATEGORY_ERROR', $category_error);
		$page->SetParameter ('TITLE_FIELD', $title_field);
		$page->SetParameter ('DESC_FIELD', $desc_field);
		$page->SetParameter ('TITLE_COUNT', (80-strlen($title_field)));
		$page->SetParameter ('DESC_COUNT', (400-strlen($desc_field)));
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Submit Story'));
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->SetParameter ('STORY_URL_FIELD', $_POST['story_url']);
		$page->CreatePageEcho($lang,$config);
	}
}
else
{
	// Output Step 1 of add story template
	$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/add_story_step1.html");
	$page->SetLoop ('CATS', $cats);
	$page->SetParameter ('FIELD_URL','http://');
	$page->SetParameter ('URL_ERROR','');
	$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,'Submit Story'));
	$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
	$page->CreatePageEcho($lang,$config);
}
?>